<?php 

namespace Common\Service;

// 商城转盘活动
Class MallActivityTurntableService extends BaseService
{	

	/** 
	 	id, title, start_time, end_time, status, create_time,
	 	user_times, share_max, share_plus
	 	[ prize:  [ { object_id: 1, object: (MallActivityTurntableService), level: 一等奖, name: iPhone6Plus, worth: 100元, rate: 0.1%, max:2 },{}    ] ]
	 */
	
	protected $_validate = array(
		array('prize', 'checkPrize', '奖品格式错误', self::VALUE_VALIDATE, 'callback'),
	);
	
	protected $_auto = array(
        array('user_times', 'intval', self::MODEL_BOTH, 'function'),
        array('share_max', 'intval', self::MODEL_BOTH, 'function'),
        array('share_plus', 'intval', self::MODEL_BOTH, 'function'),
        array('status', 'intval', self::MODEL_BOTH, 'function'),
        array('create_time', NOW_TIME, self::MODEL_INSERT),
        array('update_time', NOW_TIME, self::MODEL_BOTH),
    );  

    public function info($id)
    {
        return $this->where(['id' => (int)$id])->find();
    }

    public function getLatest()
    {
        $map = ['status' => 1];
        return $this->where($map)->order('id desc')->find();
    }

    public function checkPrize()
    {
    	$prize = I('prize');
    	$res = explode("\r\n", $prize);
    	if (count($res) != 5) return false;
    	$allrate = 0;
    	foreach ($res as $key => $value) {
    		list($rate, $limit) = explode("|", $value);
    		$allrate += $rate;
    		if ($allrate > 1) return false;
    		if ($limit)
    		{
    			list($key, $value) = explode("=", $limit);
    			if ($key != 'limit') return false;
    		}
    	}
    	return true;
    }

}